package com.qywx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qywx.dao.DepartmentDao;
import com.qywx.dao.UserDao;
import com.qywx.entity.DepartmentEntity;
import com.qywx.entity.UserEntity;
import com.qywx.service.DepartmentService;
import com.qywx.utils.DeptTree;
import com.qywx.utils.R;
import com.qywx.utils.RestTemplateUtil;
import com.qywx.utils.TreeUtil;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @ClassName DepartmentServiceImpl
 * @Description: TODO
 * @Author wmj
 * @Date 2020/3/2
 * @Version V1.0
 **/

@Service("departmentService")
public class DepartmentServiceImpl implements DepartmentService {

    private final static Logger log = LoggerFactory.getLogger(DepartmentServiceImpl.class);

    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Autowired
    UserDao userDao;
    @Autowired
    UserServiceImpl userServiceImpl;

    @Override
    @Transactional
    public R save(DepartmentEntity department) {
        Long parentid = department.getParentid();
        //判断父部门是否存在
        if (parentid == null) {
            return R.error("请选择父部门");
        }
        DepartmentEntity dep = departmentDao.selectByParentid(parentid);
        if (dep == null) {
            return R.error("父部门不存在");
        }
        //判断部门名称是否输入
        String name = department.getName();
        if (name == null) {
            return R.error("请输入部门名称");
        }
        //判断部门是否已经存在
        List<DepartmentEntity> departmentEntityList = departmentDao.findByNameAll(name);
        if (departmentEntityList.size()>0) {
            return R.error("部门已存在");
        }
        department.setIsSynchronize("0");
        //同步部门信息到微信端
        String accessToken = restTemplateUtil.getaccessToken();//获取access_token
        if (accessToken != null) {
            //保存部门到企业微信
            String url = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=" + accessToken;
            Map resultMap = restTemplateUtil.postRequest(url, department);
            Integer code = (Integer) resultMap.get("errcode");
            String errmsg = (String) resultMap.get("errmsg");
            log.info("===========保存部门到微信端返回信息===========" + errmsg, errmsg);
            if (0 == code) {
                Integer id = (Integer) resultMap.get("id");
                long longValue = id.longValue();
                department.setId(longValue);
                department.setIsSynchronize("1");
                departmentDao.save(department);
            } else {
                return R.error("保存部门到微信失败,请点击同步按钮再次进行同步");
            }
        } else {
            return R.error("获取access_token失败");
        }
        return R.ok();
    }

    @Override
    public List<DepartmentEntity> findByName(String name) {
        List<DepartmentEntity> departmentEntity = departmentDao.findByName(name);
        return departmentEntity;
    }

    @Override
    @Transactional
    public R updateDepartment(DepartmentEntity departmentEntity) {
        departmentDao.updateById(departmentEntity);
        String accessToken = restTemplateUtil.getaccessToken();
        if (accessToken != null) {
            //更新部门到企业微信
            String url = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=" + accessToken;
            Map resultMap = restTemplateUtil.postRequest(url, departmentEntity);
            Integer code = (Integer) resultMap.get("errcode");
            String errmsg = (String) resultMap.get("errmsg");
            log.info("===========保存部门到微信端返回信息===========" + errmsg, errmsg);
            if (0 != code) {
                departmentEntity.setIsSynchronize("2");
                departmentDao.updateById(departmentEntity);
                return R.error("更新部门到微信失败,请点击同步按钮再次进行同步");
            }
        } else {
            return R.error("获取access_token失败");
        }
        return R.ok();
    }

    @Override
    @Transactional
    public R delDepartmentById(Long id) {
        int depid = id.intValue();
        DepartmentEntity departmentEntity = departmentDao.selById(depid);
        //判断是否有子部门
        List<DepartmentEntity> children = departmentDao.findChildren(id);
        if (children.size() > 0) {
            return R.error("该部门存在子部门或者成员，不能删除");
        }
        //判断部门下是否有成员
        List<UserEntity> byDepartmentId = userDao.findByDepartmentId(depid, 0, 10,"");
        if (byDepartmentId.size() > 0) {
            return R.error("该部门存在子部门或者成员，不能删除");
        }
        //备份
        departmentDao.backups(departmentEntity);
        //删除
        departmentDao.deleteById(id);
        //同步删除微信端
        String accessToken = restTemplateUtil.getaccessToken();
        if (accessToken != null) {
            //保存用户到企业微信
            String url = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=" + accessToken + "&id=" + id;
            //发起请求
            Map resultMap = restTemplate.getForObject(url, Map.class);
            Integer code = (Integer) resultMap.get("errcode");
            String errmsg = (String) resultMap.get("errmsg");
            log.info("===========同步删除微信部门返回信息===========" + errmsg, errmsg);
            if (0 != code) {
                return R.error("同步删除微信部门失败,请点击同步按钮再次进行同步");
            }
        } else {
            return R.error("获取access_token失败");
        }
        return R.ok();
    }

    @Override
    public List<DepartmentEntity> getDepartmentList() {
        List<DepartmentEntity> departmentEntityList = departmentDao.getDepartmentList();
        DeptTree menuTree = new DeptTree(departmentEntityList);
        departmentEntityList = menuTree.builTree();
        return departmentEntityList;
    }

    @Override
    public R asynchronousDetection() {
        String count = departmentDao.asynchronousDetection();
        return R.ok(count);
    }

    @Override
    public R synchronize() {
        List<DepartmentEntity> departmentEntityList = departmentDao.synchronize();
        for (int i = 0; i < departmentEntityList.size(); i++) {
            DepartmentEntity departmentEntity = departmentEntityList.get(i);
            String isSynchronize = departmentEntity.getIsSynchronize();
            String accessToken = restTemplateUtil.getaccessToken();
            if ("0".equals(isSynchronize)) {
                String url = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=" + accessToken;
                Map resultMap = restTemplateUtil.postRequest(url, departmentEntity);
                Integer code = (Integer) resultMap.get("errcode");
                String errmsg = (String) resultMap.get("errmsg");
                log.info("===========保存部门到微信端返回信息===========" + errmsg, errmsg);
                if (0 == code) {
                    departmentEntity.setIsSynchronize("1");
                    departmentDao.updateById(departmentEntity);
                } else {
                    return R.error("保存部门到微信失败");
                }
            } else {
                String url = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=" + accessToken;
                Map resultMap = restTemplateUtil.postRequest(url, departmentEntity);
                Integer code = (Integer) resultMap.get("errcode");
                String errmsg = (String) resultMap.get("errmsg");
                log.info("===========更新部门到微信失败返回信息===========" + errmsg, errmsg);
                if (0 == code) {
                    departmentEntity.setIsSynchronize("1");
                    departmentDao.updateById(departmentEntity);
                } else {
                    return R.error("更新部门到微信失败,请点击同步按钮再次进行同步");
                }
            }
        }
        return R.ok();
    }

    @Override
    public R findChildren(Long id) {
        List<DepartmentEntity> departmentEntityList = departmentDao.findChildren(id);
        R r = new R();
        r.put("data", departmentEntityList);
        return r;
    }

    @Override
    @Transactional
    public R delUser(String userid, Long departmentid) {
        String[] split = userid.split(",");
        for (int i = 0; i < split.length; i++) {
            //删除部门成员
            departmentDao.delByDepIdAndUserid(split[i], departmentid);
            //判断用户是否不属于任何部门
            List<Integer> list = departmentDao.selByUserid(split[i]);
            if (list.size() < 1) {
                //用户不属于任何部门，把用户设置为无效
                userDao.updateStat(split[i]);
                //删除用户标签关系
                userDao.delUserTad(split[i]);
                //同步删除微信端
                List<String> idList = new ArrayList<>();
                idList.add(split[i]);
                String accessToken = restTemplateUtil.getaccessToken();
                String url = "https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete?access_token=" + accessToken;
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("useridlist", idList);
                //设置请求头
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                //请求体
                HttpEntity<String> formEntity = new HttpEntity<String>(jsonObject.toString(), headers);
                //发起请求
                Map resultMap = restTemplate.postForObject(url, formEntity, Map.class);
                Integer code = (Integer) resultMap.get("errcode");
                String errmsg = (String) resultMap.get("errmsg");
                log.info("===========删除微信用户返回信息===========" + errmsg, errmsg);
                if (0 != code) {
                    R.error("删除微信用户失败");
                }
            } else {
                //用户至少属于一个部门，更新微信端用户
                UserEntity userEntity = userDao.selectDetailById(split[i]);
                userServiceImpl.updateWechat(userEntity);
            }
        }
        return R.ok();
    }

    @Override
    @Transactional
    public R saveDepartUser(String userids, Long departmentid) {
        String[] split = userids.split(",");
        int depid = departmentid.intValue();
        for (int i = 0; i < split.length; i++) {
            int count = userDao.selByUseridAndDepid(split[i], depid);
            if (count > 0) {
                continue;
            }
            //添加部门用户
            userDao.saveDepUser(depid, split[i]);
            //更新到微信端
            UserEntity userEntity = userDao.selectDetailById(split[i]);
            //user表中更新department字段
            String department = userEntity.getDepartment();
            department = department + departmentid + ",";
            userEntity.setDepartment(department);
            userDao.updateById(userEntity);
            userServiceImpl.updateWechat(userEntity);
        }
        return R.ok();
    }

    @Override
    public R getDepartBydepid(int depid) {
        DepartmentEntity departmentEntity = departmentDao.selById(depid);
        departmentEntity.setLabel(departmentEntity.getName());
        List<DepartmentEntity> departmentEntityList = new ArrayList<>();
        departmentEntityList.add(departmentEntity);
        R r = new R();
        r.put("data", departmentEntityList);
        return r;
    }
}
